package com.fanghuaiming.seata.order.service.impl;

import com.fanghuaiming.seata.order.dao.mapper.SeataTccOrderMapper;
import com.fanghuaiming.seata.order.dao.model.SeataTccOrder;
import com.fanghuaiming.seata.order.service.OrderService;
import com.fanghuaiming.seata.order.spi.account.SeataAccountFeignClient;
import com.fanghuaiming.seata.order.spi.item.SeataItemFeignClient;
import com.fanghuaiming.seata.order.tcc.SeataPhaseTccOrder;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/****
 * @description: 订单服务接口实现类
 * @version:1.0.0
 * @author fanghuaiming
 * @data Created in 2020/11/27 下午1:59
 *
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    /**
     * 商品mapper
     */
    @Autowired
    private SeataTccOrderMapper seataTccOrderMapper;

    /**
     * 账户微服务SPI
     */
    @SuppressWarnings("all")
    @Autowired
    private SeataAccountFeignClient seataAccountFeignClient;

    /**
     * 商品微服务SPI
     */
    @SuppressWarnings("all")
    @Autowired
    private SeataItemFeignClient seataItemFeignClient;

    /**
     * 二阶段提交组件
     */
    @Autowired
    private SeataPhaseTccOrder seataPhaseTccOrder;

    /**
     * @Description: 下订单服务
     *
     * @param:
     * @return:
     * @auther: fanghuaiming
     * @date: 2020/11/27 下午2:51
     * @version:1.0.0
     */
    @SuppressWarnings("all")
    @GlobalTransactional
    @Override
    public void create(SeataTccOrder seataTccOrder) {
        //userId=1&productId=1&count=10&money=100
        seataTccOrder.setId(1L);

        //不再直接执行数据库操作
        //seataTccOrderMapper.create(order);

        //调用TCC 第一阶段方法
        // JDK代理调用的 AOP 生成动态代理对象，拦截器会自动创建context 对象
        seataPhaseTccOrder.prepareCreateOrder(null,
                seataTccOrder.getId(),
                seataTccOrder.getUserId(),
                seataTccOrder.getProductId(),
                seataTccOrder.getCount(),
                seataTccOrder.getMoney());

        // 扣减库存
        seataItemFeignClient.decreaseItem(seataTccOrder.getProductId(), seataTccOrder.getCount());

        //扣减账户余额
        seataAccountFeignClient.decreaseAccount(seataTccOrder.getUserId(), seataTccOrder.getMoney());

    }



}
